#!/usr/bin/env python
# -*- coding: utf-8 -*-

import gtk
import gtk.glade
from gettext import gettext as _

from gnomeagenda.ui.AccelEntry import AccelEntry
from gnomeagenda import APP_VERSION, APP_NAME,GLADEFILE
from gnomeagenda import Keybinder
from gnomeagenda.pluginsystem import *

class PrefDialog:
	def __init__(self,database,agenda):
		self._database = database
		self._agenda = agenda
		self.wTree = gtk.glade.XML(GLADEFILE)
		self.dlg = self.wTree.get_widget("preferencedialog")
		
		print self.get_config('num_days')
		pass
	def on_activate_provider(self,widget = None, provider = None,cals = []): 
		try:
			page = self.wTree.get_widget("%s_page" %(provider.__module__))
			
			if(widget.get_active()):
				page.show()
			else:
				page.hide()				
		except Exception,e:
			pass
		pass
		
	def on_calendar_toggled_cb(self,cell, path, user_data):
		"""Callback for activating/deavtivating a calendar""" 
		model, column = user_data
		model[path][column] = not model[path][column]
		calendar_id = model[path][0]
		database.setCalendarHidden(calendar_id,model[path][column])
		return
		
	def mk_calendar_treeview(self,provider):
		calendars = self._database.getCalendars(provider)
		#liststore: ID, visible, name
		liststore = gtk.ListStore(gobject.TYPE_STRING,gobject.TYPE_BOOLEAN,gobject.TYPE_STRING)
		treeview = gtk.TreeView(liststore)
		treeview.set_headers_visible(False)
		
		bool_cell = gtk.CellRendererToggle()
		bool_cell.set_property("activatable", True)

		bcolumn = gtk.TreeViewColumn('')
		bcolumn.pack_start(bool_cell)
		bcolumn.add_attribute(bool_cell,'active',1)
		bool_cell.connect("toggled", self.on_calendar_toggled_cb, (liststore, 1))
		
		
		name_col = gtk.TreeViewColumn('')
		
		treeview.append_column(bcolumn)
		treeview.append_column(name_col)
		name_cell = gtk.CellRendererText()

		name_col.pack_start(name_cell)
		name_col.add_attribute(name_cell,'markup',2)

		for row in calendars:
			#TODO: get the visible flag from the calendar
			active = True
			if (row[6] != 0):
				active = False
			liststore.append([row[0],active,row[1]])
		return treeview

	def on_keyboard_shortcut_entry_changed(self, entry, accel_name, keyval, mods, keycode):        
		if accel_name != "":
			self._agenda.set_keybinding(accel_name)
			self._agenda.bind_keybinding(accel_name)
		return False
	def get_config(self,path):
		"""
		get a value from the configuration file
		"""
		return self._database.get_option(path)

	def set_config(self,path,value):
		return self._database.set_option(path,value)
	def run(self):
		#dynamically build the list of active sources
		
		providers = get_by_capability('provider')
		active_providers = []
		active_providers = self.get_config('active_providers')
		
		#Populate the active calendar tree
		active_calendar_box = self.wTree.get_widget("active_calendar_box")

		sql = "select distinct provider from Calendar"
		active_calendar_sources = []
		for provider in providers:
			
			l = gtk.Label()
			l.set_markup('<b>%s</b>' % provider.Plugin_Name)
			l.set_alignment(0,0.5)
			
			checkbox = gtk.CheckButton()
			checkbox.add(l)

			active = provider.__module__ in active_providers
			
			checkbox.connect("toggled",self.on_activate_provider,provider)
			checkbox.set_active(active)	
			checkbox.emit("toggled")
			checkbox.set_data('module',"%s" % provider.__module__)
			
			active_calendar_box.pack_start(checkbox,False,False)
			treeview = self.mk_calendar_treeview(provider.__module__)
			active_calendar_box.pack_start(treeview,False,False)
			
			active_calendar_sources.append(checkbox)
			
		active_calendar_box.show_all()
		
		keybinding_entry_container = self.wTree.get_widget("keybinding_entry_container")
		if(Keybinder):
			keyboard_shortcut_entry = AccelEntry()
			keyboard_shortcut_entry.connect('accel-edited', self.on_keyboard_shortcut_entry_changed)
			keyboard_shortcut_entry.get_widget().show()
			keybinding_entry_container.pack_start(keyboard_shortcut_entry.get_widget(), True)
			keyboard_shortcut_entry.set_accelerator_name(self.get_config('accelerator'))
		else:
			keybinding_entry_container.hide()
		pref_refresh = self.wTree.get_widget("pref_refresh")
		pref_reminder = self.wTree.get_widget("pref_reminder")	
		pref_width = self.wTree.get_widget("pref_width")
		pref_height = self.wTree.get_widget("pref_height")
	
		pref_days = self.wTree.get_widget("pref_days")
			
		#google-calendar
		try:
			pref_gcal_username = self.wTree.get_widget("pref_gcal_username")
			pref_gcal_password = self.wTree.get_widget("pref_gcal_password")
			pref_gcal_username.set_text(self.get_config('plugins/GoogleCalendar/username'))
			pref_gcal_password.set_text(self.get_config('plugins/GoogleCalendar/password'))
		except:
			pass
		#groupwise
		try:
			pref_gw_server			 = self.wTree.get_widget("pref_gw_server")
			pref_gw_username		   = self.wTree.get_widget("pref_gw_username")
			pref_gw_password		   = self.wTree.get_widget("pref_gw_password")
			pref_gw_connection_ssl  = self.wTree.get_widget("pref_gw_connection_ssl")
			pref_gw_connection_normal	   = self.wTree.get_widget("pref_gw_connection_normal")
			pref_gw_port_normal	 = self.wTree.get_widget("pref_gw_port_normal")
			pref_gw_port_ssl		   = self.wTree.get_widget("pref_gw_port_ssl")
			pref_gw_folder			 = self.wTree.get_widget("pref_gw_folder")
			pref_gw_tzadjust		   = self.wTree.get_widget("pref_gw_tzadjust")

			pref_gw_server.set_text(self.get_config('plugins/Groupwise/server'))
			pref_gw_username.set_text(self.get_config('plugins/Groupwise/username'))
			pref_gw_password.set_text(self.get_config('plugins/Groupwise/password'))
			if(bool(self.get_config('plugins/Groupwise/ssl'))):
				pref_gw_connection_ssl.set_active(True)
			else:
				pref_gw_connection_normal.set_active(True)
			pref_gw_port_normal.set_value(float(self.get_config('plugins/Groupwise/port_normal')))
			pref_gw_port_ssl.set_value(float(self.get_config('plugins/Groupwise/port_ssl')))
			pref_gw_folder.set_text(self.get_config('plugins/Groupwise/folder'))
			pref_gw_tzadjust.set_value(float(self.get_config('plugins/Groupwise/timezoneadjust')))
		except:
			pass
		
		pref_refresh.set_value(float(self.get_config('refresh')))
		pref_reminder.set_value(float(self.get_config('reminder')))

		
		pref_height.set_value(float(self.get_config('height')))
		pref_width.set_value(float(self.get_config('width')))
		
		pref_days.set_value(float(self.get_config('num_days')))
		#get_active()
		#process the settings
		result = self.dlg.run()
		settings = {}
		if(result):
			settings['active_providers'] = []
			for prov_checkbox in active_calendar_sources:
				if(prov_checkbox.get_active()):
					settings['active_providers'].append(prov_checkbox.get_data('module'))
			self.set_config('active_providers',settings['active_providers'])
			#google-calendar
			try:
				self.set_config('plugins/GoogleCalendar/username',pref_gcal_username.get_text())
				self.set_config('plugins/GoogleCalendar/password',pref_gcal_password.get_text())
			except:
				pass
			#groupwise
			try:
				self.set_config('plugins/Groupwise/server', pref_gw_server.get_text())
				self.set_config('plugins/Groupwise/username', pref_gw_username.get_text())
				self.set_config('plugins/Groupwise/password', pref_gw_password.get_text())
				self.set_config('plugins/Groupwise/ssl', pref_gw_connection_ssl.get_active())
				self.set_config('plugins/Groupwise/port_normal', pref_gw_port_normal.get_text())
				self.set_config('plugins/Groupwise/port_ssl',pref_gw_port_ssl.get_text())
				self.set_config('plugins/Groupwise/folder',pref_gw_folder.get_text())			 
				self.set_config('plugins/Groupwise/timezoneadjust',pref_gw_tzadjust.get_text())					   
			except:
				pass
			self.set_config('refresh',pref_refresh.get_text())
			self.set_config('reminder',pref_reminder.get_text())
			
			self.set_config('width',pref_width.get_text())
			self.set_config('height',pref_height.get_text())
			self.set_config('num_days',pref_days.get_text())
			
			self.write()
		self.dlg.destroy()
		
		self._database.initializeProviders()
		return result
	def write(self):
		"""
		write the configuration
		"""
		self._database.settings.write()